package com.yuand.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yuand.core.RedisCache;
import com.yuand.entity.LoginUser;
import com.yuand.entity.SysUser;
import com.yuand.service.LoginService;
import com.yuand.utils.JwtUtils;
import com.yuand.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @ClassName: LoginServiceImpl
 * @Author: yuandong
 * @Date 2022/1/14 15:26
 */
@Service
@Slf4j
public class LoginServiceImpl  implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(SysUser user) {

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());

        System.out.println("进入loginService中的login() 方法了.......");
        //后续会执行UserDetailsServiceImpl的方法（数据库查询是否存在该用户，并返回一个UserDetails对象,也就是自己定义的LoginUser,这个loginUser对象会被封装到Authentication对象中）
        //从UserDetailsServiceImpl查询出该用户对应的菜单权限
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        log.info("又回到login()方法了，把用户的信息全部封装到了Authentication里面了:"+authenticate);

        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        String userId = loginUser.getUser().getUserId().toString();
        String token = JwtUtils.generate(userId,1000*60*60);  //生成token，有效期为1分钟

        log.info("后台生成的token>>>>>>"+token);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId, loginUser);

        //把token响应给前端
        JSONObject result = new JSONObject();
        result.put("token",token);
        result.put("username",loginUser.getUsername());
        result.put("user",loginUser.getUser());
        return new ResponseResult(200,"登陆成功",result);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getUserId();
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200,"退出成功");
    }
}
